package com.xiaoai.io.nio2ChannelTest;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * nio 核心channel
 *
 * @Author
 * @Date 2021-09-11 23:05
 */
public class ChannelTest {
    @Test
    public void read() {
        try {
            FileInputStream fis = new FileInputStream("data01.txt");
            // 获取channel
            FileChannel channel = fis.getChannel();
            // 定义缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 读取数据到缓冲区
            channel.read(buffer);
            buffer.flip();
            String rs = new String(buffer.array(), 0, buffer.remaining());
            System.out.println("读取文件数据："+rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void write(){
        try {
            FileOutputStream fos = new FileOutputStream("data01.txt");
            // 获取channel
            FileChannel channel = fos.getChannel();
            // 定义缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put("hello,world!".getBytes());
            // 将缓冲区改为写模式
            buffer.flip();
            // 通过channel写出数据
            channel.write(buffer);
            channel.close();
            System.out.println("数据写出到文件!");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




}
